package com.cheer.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.cheer.entity.Applicant;
import com.cheer.enums.TrueOrFalseEnum;
import com.cheer.exception.ServiceException;
import com.cheer.param.IdsParam;
import com.cheer.param.ReferenceInOrUpParam;
import com.cheer.param.ApplicantSpecialParam;
import com.cheer.security.UserInfoHolder;
import com.cheer.service.AdminService;
import com.cheer.service.ApplicantService;
import com.cheer.service.ReferencePlacesService;
import com.cheer.service.ReferenceService;
import com.cheer.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.rmi.ServerException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 台账信息表
 *
 * @author chufangzheng
 * @email 1280251739@qq.com
 * @date 2022-02-16 08:58:00
 */
@Api(tags = "ReferenceController", description = "参评类")
@RestController
@RequestMapping("reference")
public class ReferenceController {

    @Autowired
    private ReferenceService referenceService;

    @Autowired
    private UserInfoHolder userInfoHolder;

    @Autowired
    private ApplicantService applicantService;

    @Autowired
    private ReferencePlacesService referencePlacesService;

    @Autowired
    private AdminService adminService;

    @ApiOperation("参评信息列表")
    @GetMapping("/list")
    public Result list( Long applicantId ) throws IOException {

        Applicant applicant;
        if(applicantId != null){
            applicant = applicantService.getById(applicantId);
        }else{
            applicant = applicantService.getEntityByAccountId(userInfoHolder.getAccountId());
        }
        if(applicant == null){
            throw new ServerException("未查询到当前集体");
        }
        List<ReferenceListVO> referenceListVOList = referenceService.list(applicant.getId());
        return Result.success(referenceListVOList);
    }

    @ApiOperation(value = "进度提示", notes = "1 注册创建：注册创建成功，请等待上级审批机构对您的审核。\n" +
            "2市级文明号参评：市级文明号参评进行中，请及时登录系统查看进度。\n" +
            "3市级文明号命名成功：市级青年文明号命名成功，您可以（等待省级文明号创建阶段）继续提交‘省级青年文明号创建申请’。\n" +
            "4省级文明号创建：省级文明号创建成功，您正在参与省级青年文明号创建工作，日常台账信息将作为参评命名重要参考依据，欢迎继续填报完善台账信息。\n" +
            "5省级文明号参评：省级文明号参评成功，市级审核机构将收到您的提交信息，请及时登录系统查看进度。\n" +
            "7省级文明号参评（不通过）：省级文明号参评未通过，请点击审核日志查看原因。\n" +
            "6市级文明号命名：恭喜你，省级文明号命名成功。")
    @PostMapping("/hint")
    public Result hint() {

        Map<String, Integer> hint = new HashMap<>();
        Integer code = applicantService.getHint();
        hint.put("hintCode",code);

        return Result.success(hint);
    }


    /**
     * 省级文明号申请
     */
    @GetMapping("/apply")
    @ApiOperation("参评申请")
    public Result<Map> apply(Integer reviewType, Long joinReviewOrgId) {

        Map<String, Boolean> resultMap = new HashMap<>();
        try {
            referenceService.updateOrg(userInfoHolder.getAccountId(), reviewType, joinReviewOrgId);
            resultMap.put("isSuccess", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("isSuccess", false);
        }
        return Result.success(resultMap);
    }

    @ApiOperation("删除参评信息")
    @PostMapping("/delete")
    public Result delete(@RequestBody IdsParam idsParam){
        if(idsParam == null){
            throw new ServiceException("未选中要删除的内容！");
        }
        if(CollectionUtil.isNotEmpty(idsParam.getIds())){
            referenceService.removeByIds(idsParam.getIds());
        }
        return Result.success();
    }


    @ApiOperation(value = "集体参评审核分页", notes = "vintage 年份， orgId 机构， " +
            "isPost 是否报送， registerStatus 文明号级别  contactPerson 负责人  applicantName 集体名称  isSubmitAgain 是否是驳回后提交")
    @GetMapping("/applicant/list")
    public Result<Page<ApplicantReferenceListVO>> applicantReferenceList(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                            @RequestParam(required = false) Integer vintage,
                                                            @RequestParam(required = false) Long orgId,
                                                            @RequestParam(required = false) Integer isPost,
                                                            @RequestParam(required = false) Integer registerStatus,
                                                            @RequestParam(required = false) String contactPerson,
                                                            @RequestParam(required = false) String applicantName,
                                                            @RequestParam(required = false) Integer isSubmitAgain) {
        if(TrueOrFalseEnum.TRUE.getType().equals(isSubmitAgain)){
            Page<ApplicantReferenceListVO> page = applicantService.submitAgain(pageNum, pageSize,  userInfoHolder.getAdminOrgId());
            return Result.success(page);
        }
        if (orgId == null) {
            orgId = userInfoHolder.getAdminOrgId();
        }
        Page<ApplicantReferenceListVO> page = applicantService.getApplicantReferenceList(pageNum, pageSize, vintage, orgId, isPost, registerStatus, applicantName, contactPerson);
        return Result.success(page);
    }

    @ApiOperation(value = "已驳回再次提交数量")
    @GetMapping("/submit/again/number")
    public Result<Integer> submitAgainNumber() {

        Integer submitAgainNumber = applicantService.submitAgainNumber(userInfoHolder.getAdminOrgId());
        return Result.success(submitAgainNumber);
    }

    @ApiOperation(value = "机构名额信息")
    @GetMapping("/org/places/information")
    public Result<ReferencePlacesVO> placesInformation() {

        ReferencePlacesVO referencePlacesVO = referencePlacesService.placesInformation();
        return Result.success(referencePlacesVO);
    }


    @ApiOperation(value = "团省委名额查看", notes = "orgId 机构ID  vintage 年份")
    @GetMapping("/tsw/places/information")
    public Result tswPlacesInformation(Long orgId, String vintage)  {

        if (orgId == null) {
            orgId = userInfoHolder.getAdminOrgId();
        }
        ReferencePlacesTswVO referencePlacesTswVO = referencePlacesService.tswPlacesInformation(orgId, vintage);
        return Result.success(referencePlacesTswVO);
    }


    @ApiOperation(value = "首页名额展示", notes = "orgId 机构ID  vintage 年份")
    @GetMapping("/tsw/places/index")
    public Result tswPlacesIndex()  {

        ReferencePlacesIndexVO referencePlacesIndexVO = referencePlacesService.tswPlacesIndex(DateUtil.format(new Date(), "yyyy"));
        return Result.success(referencePlacesIndexVO);
    }

    @ApiOperation("参评excel导出")
    @GetMapping("/applicant/export")
    public void applicantReferenceExport( @RequestParam(required = false) Integer vintage,
                                          @RequestParam(required = false) Long orgId,
                                          @RequestParam(required = false) Integer isPost,
                                          @RequestParam(required = false) Integer registerStatus,
                                          @RequestParam(required = false) String contactPerson,
                                          @RequestParam(required = false) String applicantName) {
        if (orgId == null) {
            orgId = userInfoHolder.getAdminOrgId();
        }
        applicantService.applicantReferenceExport(vintage, orgId, isPost, registerStatus, applicantName, contactPerson);
    }


    @ApiOperation("保存参评信息")
    @PostMapping("/save")
    public Result save( @RequestBody @Valid ReferenceInOrUpParam referenceInOrUpParam ){
        referenceService.save(referenceInOrUpParam);
        return Result.success();
    }


    @ApiOperation("参评详情")
    @GetMapping("/detail")
    public Result detail()  {
        ReferenceDetailVO referenceDetailVO =  referenceService.detail();
        return Result.success(referenceDetailVO);
    }

    @ApiOperation("置顶或者取消置顶")
    @PostMapping("/topOrCancel")
    public Result topOrCancel(@RequestBody IdsParam idsParam)  {
        referenceService.topOrCancel(idsParam);
        return Result.success();
    }

    @ApiOperation("报送团省委")
    @PostMapping("/postTsw")
    public Result postTsw(@RequestBody IdsParam idsParam)  {
        referenceService.postTsw(idsParam);
        return Result.success();
    }

    @ApiOperation("授予文明号")
    @PostMapping("/confer")
    public Result confer(@RequestBody IdsParam idsParam)  {
        referenceService.confer(idsParam);
        return Result.success();
    }

    @ApiOperation("驳回")
    @GetMapping("/deny")
    public Result deny(Long applicantId, String cause)  {
        referenceService.deny(applicantId, userInfoHolder.getAccountId(), userInfoHolder.getAdminOrgId(), cause);
        return Result.success();
    }

    @ApiOperation("创建名额")
    @GetMapping("/create/places")
    public Result createPlaces()  {
        referencePlacesService.createPlaces();
        return Result.success();
    }

    @ApiOperation("特殊推荐")
    @PostMapping("/special/recommend")
    public Result specialRecommend(@RequestBody @Valid ApplicantSpecialParam specialApplicantVO)  {
        adminService.specialRecommend(specialApplicantVO);
        return Result.success();
    }


}
